<template>
  <div class="Avatar">
    <div id="AvatarBox">
      <canvas :class="'AvatarCanvas'+index" style="zoom:0.5;"></canvas>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Avatar',
  data () {
    return {
      key: 'msg'
    }
  },
  props: {
    AvatarUrl: {
      type: String
    },
    index: {
      type: Number
    }
  },
  mounted () {
    let width1STBox = document.getElementById('AvatarBox')
    let canvas = document.getElementsByClassName('AvatarCanvas' + this.index)[0]
    let ctx = canvas.getContext('2d')
    let style = window.getComputedStyle(width1STBox, null)
    let width1st = Math.round(parseInt(style.width) * 2)
    let height1st = Math.round(parseInt(style.height) * 2)
    // console.log(width1st, height1st)
    canvas.setAttribute('width', width1st + 'px')
    canvas.setAttribute('height', height1st + 'px')
    this.dramAvatar(canvas, ctx, width1st, height1st, 'https://hnres.etalk365.com/' + this.AvatarUrl)
  },
  methods: {
    dramAvatar (canvas, ctx, width, height, url) {
      canvas.setAttribute('width', width + 'px')
      canvas.setAttribute('height', height + 'px')
      let AvatarImg = new Image()
      let defaultImg = new Image()
      AvatarImg.src = url
      defaultImg.src = require('../assets/defaultA.jpg')
      let AvatarImgPromise = new Promise((resolve, reject) => {
        AvatarImg.onload = () => {
          resolve(1)
        }
        AvatarImg.onerror = () => {
          resolve(0)
        }
      })
      let defaultImgPromise = new Promise((resolve, reject) => {
        defaultImg.onload = () => {
          resolve(1)
        }
        defaultImg.onerror = () => {
          resolve(0)
        }
      })
      Promise.all([AvatarImgPromise, defaultImgPromise]).then((data) => {
        ctx.beginPath()
        ctx.save()
        ctx.arc(width / 2, height * 0.5, height * 0.35, 0, 2 * Math.PI)
        let imgWidth = height * 0.8
        let imgHeight = height * 0.8
        if (Number(data[0]) === 1) {
          ctx.clip()
          // ctx.clip() 之后 所有操作都会在这范围里面
          ctx.drawImage(AvatarImg, (width - imgWidth) * 0.5, (height - imgHeight) * 0.5, imgWidth, imgHeight)
        } else {
          ctx.clip()
          ctx.drawImage(defaultImg, (width - imgWidth) * 0.5, (height - imgHeight) * 0.5, imgWidth, imgHeight)
        }
      })
    }
  }
}
</script>

<style scoped>
.Avatar{
  width:20%;
  height:100%;
}
#AvatarBox{
  width:100%;
  height:100%;
}
</style>
